<template>
    <div>
        <van-index-bar :index-list="computeCitiesList">
            <div v-for="(item,index) in datalist" :key="index">
                <van-index-anchor :index="item.type" />
                <van-cell 
                    v-for="(city,i) in  item.list" 
                    :key="i" 
                    :title="city.name"
                    @click="handleClick(city.name,city.cityId)"
                />
            </div>
        </van-index-bar>
   </div>
</template>

<script>
import http from "@/utils/http"

import Vue from 'vue';
import { IndexBar, IndexAnchor,Cell } from 'vant';

Vue.use(IndexBar);
Vue.use(IndexAnchor);
Vue.use(Cell);

import {mapState,mapMutations,mapActions} from "vuex"
export default {
    data() {
        return {
            datalist: [],
        };
    },
    mounted () {
        http({
            url: '/gateway?k=5866904',
            headers: {
                'X-Host': 'mall.film-ticket.city.list'
            }
        }).then(res => {
            // console.log(res.data.data.cities)
            this.datalist = this.datafilter(res.data.data.cities)
        })
    },
    methods: {
        ...mapMutations("filmModule",["clearFilmData"]),
        ...mapMutations("cityModule",["updateCityName","updateCityId"]),
        ...mapMutations("cinemaModule",["clearDataList"]),

        datafilter(cities){
            
            let letterList = []
            for(let code=65;code<91;code++){
                letterList.push(String.fromCharCode(code))
            }

            let newCitiesList = []
            letterList.forEach(letter => {
                let list = cities.filter(city=>
                    city.pinyin.substr(0,1).toUpperCase() === letter 
                )
                if(list.length>0){
                        newCitiesList.push({
                        type:letter,
                        list
                    })
                }
            })
            
            return newCitiesList
        },
        handleClick(cityName,cityId){
            // this.$store.state.cityName = cityName
            // this.$store.state.cityId = cityId
            // this.$store.commit("updateCityName",cityName);
            // this.$store.commit("updateCityId",cityId);

            if(this.cityId != cityId){
                this.updateCityName(cityName);
                this.updateCityId(cityId);
                // 清空原来的filmData
                this.clearFilmData();
                this.clearDataList();
            }

	        this.$router.back()
        }
    },
    computed:{
        ...mapState('cityModule',['cityId']),
        computeCitiesList(){
            return this.datalist.map(item => item.type)
        }
    }
}
</script>